package com.example.demo.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.enums.BusinessEnum;
import com.example.demo.exception.BusinessException;
import com.example.demo.model.Json;
import com.example.demo.model.UserModel;
import com.example.demo.services.MD5EncryptionService;
import com.example.demo.services.UserService;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
public class LoginController {

    @Resource
    UserService userService;
    @Resource
    MD5EncryptionService md5EncryptionService;

    @GetMapping("back/login")
    public ModelAndView enter(
            Model model,
            HttpSession session
    ){
        try{
            return new ModelAndView("admin/login/login");
        }catch (Exception e) {
            model.addAttribute("message", e.getMessage());
            return new ModelAndView("error/message");
        }
    }



    @PostMapping("back/enter")
    public Json login(
            @RequestParam Map<String, String> params,
            HttpSession session
    ){
        try{
            if(params.get("account") == null)
            {
                throw new BusinessException(BusinessEnum.LOGIN_ACCOUNT_NULL);
            }
            if(params.get("pass") == null)
            {
                throw new BusinessException(BusinessEnum.LOGIN_PASS_NULL);
            }

            UserModel userInfo = userService.userLogin(params.get("account"), md5EncryptionService.encryption(params.get("pass")));

            if(userInfo == null)
            {
                throw new BusinessException(BusinessEnum.LOGIN_ACCOUNT_ERROR);
            }

            session.setAttribute("adminInfo", JSONObject.toJSON(userInfo));

            return new Json().success(BusinessEnum.SUCCESS);
        }catch (BusinessException e) {
            return new Json().error(e.getMessage(), e.getCode());
        }
    }

}